package org.epidroid.epidroid.androsoul.ui.contactlist;

import java.util.List;

import org.epidroid.epidroid.R;
import org.epidroid.epidroid.androsoul.engine.contacts.NetsoulContact;
import org.epidroid.epidroid.androsoul.ui.utils.TextFormater;

import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ContactAdapter extends ArrayAdapter<NetsoulContact> implements
		OnClickListener {

	private List<NetsoulContact> mItems;
	private Context mContext;

	public ContactAdapter(Context context, int textViewResourceId,
			List<NetsoulContact> dataItems) {
		super(context, textViewResourceId, dataItems);
		this.mContext = context;
		this.mItems = dataItems;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View v = convertView;
		if (v == null) {
			LayoutInflater inflater = (LayoutInflater) mContext
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = inflater.inflate(R.layout.androsoul_list_item, null);
		}

		final NetsoulContact c = this.mItems.get(position);

		TextView login = (TextView) v.findViewById(R.id.list_contact_login);
		login.setText(c.getName());

		// Change the color of the login
		if (c.getLocations().isEmpty())
			login.setTextColor(Color.WHITE);
		else if (!c.getState().equals("actif")) {
			login.setTextColor(Color.rgb(0, 125, 0));
		} else {
			login.setTextColor(Color.GREEN);
		}

		// Change the background color of the contact
		if (c.getLocations().isEmpty())
			v.setBackgroundColor(Color.rgb(0, 0, 0));
		else
			v.setBackgroundColor(Color.rgb(25, 25, 25));

		ImageView imglock = (ImageView) v
				.findViewById(R.id.list_contact_imglock);
		if (c.getState().equals("lock"))
			imglock.setVisibility(View.VISIBLE);
		else
			imglock.setVisibility(View.INVISIBLE);

		TextView loc = (TextView) v.findViewById(R.id.list_contact_location);
		String content = "";
		if (c.getLocations().size() > 0) {
			content = TextFormater.reduceString(c.getLocations().get(0)
					.getBestLocation(), 17);
			content += " - " + c.getLocations().get(0).getIp();
		} else {
			content = "Offline";
		}
		loc.setText(content);

		// Set the contact image
		ImageView img = (ImageView) v
				.findViewById(R.id.list_contact_imgcontact);
		Drawable tmp = c.getImage(mContext, false);
		if (tmp != null)
			img.setImageDrawable(tmp);
		else
			img.setImageResource(R.drawable.contact_picture_2);

		return (v);
	}

	@Override
	public void onClick(View v) {
	}
}
